package controller

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo/v4"
	"github.com/labstack/gommon/log"
	"law_case_api/dto"
	"law_case_api/models"
	"law_case_api/services"
	"law_case_api/utils"
	"net/http"
	"strconv"
	"time"
)

// @Summary 创建案件信息
// @Tags 非诉讼案件管理
// @Accept plain
// @Produce plain
// @Param CreateCaseDoc body dto.CaseDocReq true " "
// @Success 200 {object} models.BaseResult
// @Failure 400 {object} models.BaseResult
// @Router /wzj/doc/create [post]
func CreateCaseDoc(c echo.Context) error {
	resp := models.BaseResult{
		Code: 200,
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*models.JwtCustomClaims)
	userid, _ := strconv.Atoi(claims.UserId)
	if userid == 0 {
		resp.Code = 400
		resp.Message = "用户信息不存在，请重新登录"
		return c.JSON(http.StatusOK, resp)
	}
	caseDocReq := dto.CaseDocReq{}
	if err := c.Bind(&caseDocReq); err != nil {
		resp.Code = 400
		resp.Message = err.Error()
		return c.JSON(http.StatusBadRequest, resp)
	}
	if caseDocReq.CaseId == 0 {
		resp.Code = 400
		resp.Message = "案件编号不能为空"
		return c.JSON(http.StatusOK, resp)
	}
	wzjCaseDoc := models.WzjCaseDoc{}
	_ = utils.MapTo(caseDocReq, &wzjCaseDoc)
	wzjCaseDoc.DocCreateDate = time.Now().Unix()
	wzjCaseDoc.DocCreateUserId = int64(userid)

	_case := services.CaseService{}
	if wzjCaseDoc.DocId > 0 {
		boolRes, err := _case.UpdateCaseDoc(wzjCaseDoc)
		if err == nil && boolRes {
			resp.Message = "更新案件文档成功"
			return c.JSON(http.StatusOK, resp)
		}
		log.Error("更新案件文档失败：", err) //增加日志信息
		resp.Code = 400
		resp.Message = "更新案件文档失败"
		return c.JSON(http.StatusOK, resp)

	} else {
		boolRes, err := _case.CreateCaseDoc(wzjCaseDoc)
		if err == nil && boolRes {
			resp.Message = "创建案件文档成功"
			return c.JSON(http.StatusOK, resp)
		}
		log.Error("创建案件文档失败：", err) //增加日志信息
		resp.Code = 400
		resp.Message = "创建案件文档失败"
		return c.JSON(http.StatusOK, resp)
	}
}

// @Summary 根据条件获取案件文档信息
// @Tags 案件管理
// @Accept plain
// @Produce plain
// @Param CaseDocList body dto.CaseDocListReq true " "
// @Success 200 {object} models.BaseResult
// @Failure 400 {object} models.BaseResult
// @Router /wzj/doc/list [get]
func CaseDocList(c echo.Context) error {
	resp := models.BaseResult{
		Code: 200,
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*models.JwtCustomClaims)
	userid, _ := strconv.Atoi(claims.UserId)
	if userid == 0 {
		resp.Code = 400
		resp.Message = "用户信息不存在，请重新登录"
		return c.JSON(http.StatusOK, resp)
	}
	caseDocListReq := dto.CaseDocListReq{}
	if err := c.Bind(&caseDocListReq); err != nil {
		resp.Code = 400
		resp.Message = err.Error()
		return c.JSON(http.StatusBadRequest, resp)
	}
	_case := services.CaseService{}
	respData, respPageCount, err := _case.GetCaseDocListByCondition(userid, caseDocListReq)
	if err != nil {
		resp.Code = 400
		return c.JSON(http.StatusOK, resp)
	}
	resp.PageCount = respPageCount
	resp.Data = respData
	return c.JSON(http.StatusOK, resp)
}
